package com.example.a17376080_dlz_finaltest;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import adapter.Comic;
import adapter.MajorAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import utils.HttpUtil;


public class Find_Fragment extends Fragment implements OnBannerListener,View.OnClickListener {
    private Context context;
    MajorAdapter adapter;
    private static final int WARM_BLOOD_TXT=1;
    private static final int FUNNY_TXT=2;
    private static final int FANTASY_TXT=3;
    private static List<Comic> findList=new ArrayList<>();
    LinearLayout tv_warm_blood,tv_funny,tv_fantasy;
    String WARM_BLOOD="http://106.14.221.71:8080/Service_dlz/comic_findType.action?several=热血";
    String FUNNY="http://106.14.221.71:8080/Service_dlz/comic_findType.action?several=搞笑";
    String FANTASY="http://106.14.221.71:8080/Service_dlz/comic_findType.action?several=玄幻";

    private Banner banner;
    private ArrayList<String> list_path;
    private ArrayList<String> list_title;
    View view;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case WARM_BLOOD_TXT:
                    adapter.notifyDataSetChanged();

                    break;
                case FUNNY_TXT:
                    adapter.notifyDataSetChanged();
                    break;
                case FANTASY_TXT:
                    adapter.notifyDataSetChanged();
                    break;
                    default:
                        break;
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.find_fragment,null);
        initView();
        context=getContext();
        //RecyclerView
        RecyclerView recyclerView=view.findViewById(R.id.find_recycle_view);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);

        recyclerView.setNestedScrollingEnabled(false);
       // LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());
        Log.d("空指针吗？", String.valueOf(layoutManager));
        recyclerView.setLayoutManager(layoutManager);
        adapter=new MajorAdapter(findList,context);
        recyclerView.setAdapter(adapter);
        //findList.clear();
        if(findList==null||findList.isEmpty()){
            startOkHttp();
        }
        return view;
    }



    //okhttp
    private void startOkHttp() {
        if (findList==null||findList.isEmpty()){
            HttpUtil.sendOkHttpRequest(WARM_BLOOD, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("热血获得数据失败","");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseData=response.body().string();
                    Log.d("热血的数据：", responseData);
                    //GSON解析
                    parseJSONWithGSON(responseData);
                    Message message=new Message();
                    message.what=WARM_BLOOD_TXT;
                    handler.sendMessage(message);
                }
            });
        }
    }
    private void parseJSONWithGSON(String jsonData) {
        findList.clear();
        Gson gson=new Gson();
        findList.addAll((Collection<? extends Comic>) gson.fromJson(jsonData,new TypeToken<List<Comic>>(){}.getType()));


    }

    private void initView() {
        banner = (Banner) view.findViewById(R.id.banner);
        //放图片地址的集合
        list_path = new ArrayList<>();
        //放标题的集合
        list_title = new ArrayList<>();

        list_path.add("http://106.14.221.71:8080/comic/ysj/fm.jpg");
        list_path.add("http://106.14.221.71:8080/comic/tyzyj/fm.jpg");
        list_path.add("http://106.14.221.71:8080/comic/swjxl/fm.jpg");
        list_path.add("http://106.14.221.71:8080/comic/fqcl/fm.jpg");
        list_title.add("妖神记");
        list_title.add("唐寅在异界");
        list_title.add("神武将星录");
        list_title.add("风起苍岚");
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //设置图片加载器，图片加载器在下方
        banner.setImageLoader(new MyLoader());
        //设置图片网址或地址的集合
        banner.setImages(list_path);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Default);
        //设置轮播图的标题集合
        banner.setBannerTitles(list_title);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER)
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                .setOnBannerListener(this)
                //必须最后调用的方法，启动轮播图。
                .start();
        //分类init
        tv_warm_blood=view.findViewById(R.id.tv_warm_blood);
        tv_funny=view.findViewById(R.id.tv_funny);
        tv_fantasy=view.findViewById(R.id.tv_fantasy);

        tv_warm_blood.setOnClickListener(this);
        tv_funny.setOnClickListener(this);
        tv_fantasy.setOnClickListener(this);
    }

    @Override
    public void OnBannerClick(int position) {
        Log.i("tag", "你点了第"+position+"张轮播图");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //热血
            case R.id.tv_warm_blood:
                findList.clear();
                if (findList==null||findList.isEmpty()){
                    HttpUtil.sendOkHttpRequest(WARM_BLOOD, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d("热血获得数据失败","");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

                            String responseData=response.body().string();
                            Log.d("热血的数据：", responseData);
                            //GSON解析
                            parseJSONWithGSON(responseData);
                            Message message=new Message();
                            message.what=WARM_BLOOD_TXT;
                            handler.sendMessage(message);
                        }
                    });
                }

                break;
            //搞笑
            case R.id.tv_funny:
                findList.clear();
                if (findList==null||findList.isEmpty()){
                    HttpUtil.sendOkHttpRequest(FUNNY, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d("搞笑获得数据失败","");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responseData=response.body().string();
                            Log.d("搞笑的数据：", responseData);
                            //GSON解析
                            parseJSONWithGSON(responseData);
                            Message message=new Message();
                            message.what=FUNNY_TXT;
                            handler.sendMessage(message);
                        }
                    });
                }


                break;
            //玄幻
            case R.id.tv_fantasy:
                findList.clear();
                if (findList==null||findList.isEmpty()){
                    HttpUtil.sendOkHttpRequest(FANTASY, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d("小玄幻获得数据失败","");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responseData=response.body().string();
                            Log.d("玄幻的数据：", responseData);
                            //GSON解析
                            parseJSONWithGSON(responseData);
                            Message message=new Message();
                            message.what=FUNNY_TXT;
                            handler.sendMessage(message);
                        }
                    });
                }

                break;
                default:
                    break;

        }

    }

    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load((String) path).into(imageView);
        }
    }
}
